from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError
from datetime import date


class ConsignmentCreateInvoiceWizard(models.TransientModel):
    _name = 'consignment.create.invoice.wizard'
    consignment_id = fields.Many2one('consignment.sales',
                                     default=lambda self: self.env.context.get('consignment_id', False))
    customer_id = fields.Many2one('res.partner', string='Customer',
                                  default=lambda self: self.env.context.get('customer_id', False))
    product_id = fields.Many2one('product.template', string='Product',
                                 default=lambda self: self.env.context.get('product_id'))
    used_qty = fields.Float(string='Used Qty', default=lambda self: self.env.context.get('used_qty'))
    unit_price = fields.Float(string='Unit Price', default=lambda self: self.env.context.get('unit_price'))
    tax_ids = fields.Many2many('account.tax', string='Taxes', default=lambda self: self.env.context.get('tax_ids'))
    create_invoice_qty = fields.Integer(string='Create Invoice Qty', default=lambda self: self.num_of_invoices)
    invoiced_qty = fields.Float(string='Invoiced Qty', default=lambda self: self.env.context.get('invoiced_qty'))
    num_of_invoices = fields.Integer(string='Can Create Invoice', compute='_get_num_of_invoices')

    @api.onchange('used_qty', 'invoiced_qty')
    def _get_num_of_invoices(self):
        self.num_of_invoices = int(self.used_qty - self.invoiced_qty)

    def confirmation(self):
        if self.create_invoice_qty <= 0 or self.create_invoice_qty > self.num_of_invoices:
            raise ValidationError(_('Create Invoice Qty must be greater than 0 and less than or equal to Invoiced Qty'))
        am_id = self.env['account.move'].create({
            'partner_id': self.customer_id.id,
            'move_type': 'out_invoice',
            'invoice_date': fields.Datetime.now(),
            'invoice_line_ids': [(0, 0, {
                'product_id': self.product_id.product_variant_id.id,
                'name': self.product_id.name,
                'price_unit': self.unit_price,
                'quantity': self.create_invoice_qty,
                'tax_ids': [(6, 0, self.tax_ids.ids)],
            })]
        })
        self.consignment_id.write({'account_move_ids': [(4, am_id.id)]})
        return {
            'type': 'ir.actions.act_window',
            'name': 'Account Move',
            'res_model': 'account.move',
            'view_mode': 'form',
            'res_id': am_id.id,
            'target': 'current',
            'views': [((False, 'form'))],
        }
